package com.xf.zk.curator.example;

import com.xf.zk.curator.constant.ZkConstant;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class BarrierTest {


	public static void main(String[] args) throws Exception {
		final String barrier_path = "/curator_recipes_barrier_path";
		// 新建客户端
		final CuratorFramework client = newClient();
		// 新建barrier
		final DistributedBarrier barrier = new DistributedBarrier(client, barrier_path);
		client.start();
		// 创建5个线程使用barrier
		barrier.setBarrier();
		for (int i = 0; i < 5; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						// 等待 barrier 移除
						barrier.waitOnBarrier();
						// 设置barrier,执行自己逻辑
						barrier.setBarrier();
						System.out.println(Thread.currentThread().getName() + "号barrier设置");
						Thread.sleep(1000);
						System.out.println("启动...");
						// 移除barrier
						barrier.removeBarrier();
					} catch (Exception e) {
					}
				}
			}).start();
		}
		barrier.removeBarrier();
		Thread.sleep(2000);
	}
	public static CuratorFramework newClient() {
		return CuratorFrameworkFactory.builder().connectString(ZkConstant.SERVER)
				.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
	}
}
